#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDialog>
#include <QDialogButtonBox>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(ui->actionSentryCheck, SIGNAL(triggered()), this, SLOT(checkSentry()));
    connect(ui->actionPunisments,  SIGNAL(triggered()), this, SLOT(editPunishments()));
    connect(ui->actionGenerate,    SIGNAL(triggered()), this, SLOT(generateMainTable()));
    connect(ui->generateButton,    SIGNAL(clicked()),   this, SLOT(generateMainTable()));

    selectMainTable();
    setDates();

    ui->centralWidget->setVisible(false);
}


void MainWindow::checkSentry()
{
    CheckSentry *cs = new CheckSentry();
    cs->exec();
    delete cs;
}


void MainWindow::editPunishments()
{
    EditPunishments *ePun = new EditPunishments();
    ePun->exec();
    delete ePun;
}


void MainWindow::selectMainTable()
{
    tableModel = new QSqlTableModel(this);
    tableModel->setTable("roster");

    tableModel->setHeaderData(Floor_ID,       Qt::Horizontal, tr("ID"));
    tableModel->setHeaderData(Day_Name,       Qt::Horizontal, tr("Day Name"));
    tableModel->setHeaderData(FirstF_First,   Qt::Horizontal, tr("FirstF_First"));
    tableModel->setHeaderData(FirstF_Second,  Qt::Horizontal, tr("FirstF_Second"));
    tableModel->setHeaderData(SecondF_First,  Qt::Horizontal, tr("SecondF_First"));
    tableModel->setHeaderData(SecondF_Second, Qt::Horizontal, tr("SecondF_Second"));
    tableModel->select();

    ui->tableView->setModel(tableModel);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectItems);
    ui->tableView->setColumnHidden(Floor_ID, true);
    ui->tableView->setColumnHidden(Day_Name, true);

    ui->tableView->resizeColumnsToContents();
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    QHeaderView *header = ui->tableView->horizontalHeader();
    header->setStretchLastSection(true);
}


void MainWindow::generateMainTable()
{
    QSqlRecord studRecord;
    QSqlRecord dayRecord;

    QSqlQuery queryForStud;

    queryForStud.exec("SELECT * FROM students ORDER BY sentryT ASC");
    queryForStud.next();

    QSqlQuery queryForDays;
    queryForDays.exec("SELECT * FROM roster");

    sentryForTheWeek = 0;
    int i;

    QString str1, str2, str3, str4;

    while(queryForDays.next())
    {
        i = 0;
        dayRecord = queryForDays.record();

        for(i = 0 ; i < 4 ; i++)
        {
            if(sentryForTheWeek >= sentryCountPerWeek)
                return;

            if(queryForStud.at() == -2) {
                queryForStud.exec("SELECT * FROM students ORDER BY sentryT ASC");
                queryForStud.next();
            }

            switch(i)
            {
                case 0:
                    studRecord = queryForStud.record();
                    str1 = studRecord.value("name").toString();
                    changeSentryCount(1, studRecord, "sentry1");
                    sentryForTheWeek++;
                    break;

                case 1:
                    studRecord = queryForStud.record();
                    str2 = studRecord.value("name").toString();
                    changeSentryCount(1, studRecord, "sentry2");
                    sentryForTheWeek++;
                    break;

                case 2:
                    studRecord = queryForStud.record();
                    str3 = studRecord.value("name").toString();
                    changeSentryCount(1, studRecord, "sentry3");
                    sentryForTheWeek++;
                    break;

                case 3:
                    studRecord = queryForStud.record();
                    str4 = studRecord.value("name").toString();

                    changeSentryCount(1, studRecord, "sentry4");
                    sentryForTheWeek++;
                    break;
            }

            queryForStud.next();

        }

        //Update Watchlist
        query.prepare("update roster    set firstFloorFirst   = :name1,  "
                      "                     firstFloorSecond  = :name2,  "
                      "                     secondFloorFirst  = :name3,  "
                      "                     secondFloorSecond = :name4  where id = :id"   );
        query.bindValue(":name1", str1);
        query.bindValue(":name2", str2);
        query.bindValue(":name3", str3);
        query.bindValue(":name4", str4);
        query.bindValue(":id", dayRecord.value("id").toString());
        query.exec();
    }

    selectMainTable();
    setDates();
}


void MainWindow::changeSentryCount(int change, QSqlRecord record, QString sType)
{
    int newNumber = record.value(sType).toInt() + change;
    int newNumberT = record.value("sentryT").toInt() + change;

    query.prepare("update students set " + sType + " = :sentry, sentryT = :sentryT           where id = :id"  );
    query.bindValue(":sentry",      newNumber);
    query.bindValue(":sentryT",     newNumberT);
    query.bindValue(":id",          record.value("id").toString());
    query.exec();
}


void MainWindow::getDate()
{
    setVisibleDateLabs(false);

    QDialog *dialog = new QDialog;
    dialog->setWindowTitle("Tarihi Gir");

    QVBoxLayout *layout = new QVBoxLayout(dialog);
    QCalendarWidget *calender = new QCalendarWidget;
    calender->setDateRange(QDate::currentDate(), QDate::currentDate().addMonths(18));
    calender->setToolTip(QString::fromUtf8("Nobet Olusturmaya Baslanilacak Tarih"));

    QPushButton *buttonOk = new QPushButton(QString::fromUtf8("Olustur"), dialog);
    buttonOk->setShown(false);

    layout->addWidget(calender);
    layout->addWidget(buttonOk);

    connect(calender, SIGNAL(selectionChanged()), buttonOk, SLOT(show()));
    connect(buttonOk, SIGNAL(clicked()),          dialog,   SLOT(close()));

    dialog->exec();

    QDate *startDate = new QDate(calender->selectedDate());

    //Startup date
    query.prepare("INSERT INTO settings (day, month, year, name)"
                  "values (:day, :month, :year, 'start')");
    query.bindValue(":day", startDate->day());
    query.bindValue(":month", startDate->month());
    query.bindValue(":year", startDate->year());
    query.exec();

    //Current Date
    query.prepare("INSERT INTO settings (day, month, year, name)"
                  "values (:day, :month, :year, 'current')");
    query.bindValue(":day",   startDate->day());
    query.bindValue(":month", startDate->month());
    query.bindValue(":year",   startDate->year());
    query.exec();
}


void MainWindow::setDates()
{
    //Set Dates
    query.exec("SELECT * FROM settings WHERE name = 'current'");
    query.next();

    QSqlRecord _record = query.record();
    int y = _record.value("year").toInt();
    int m = _record.value("month").toInt();
    int d = _record.value("day").toInt();

    QDate date(y, m, d);
    setDateLabs(date);
}


QString MainWindow::convertToString(QDate date)
{
    QString string = tr("%1.%2.%3").arg(QString::number(date.day()),
                                        QString::number(date.month()),
                                        QString::number(date.year()));
    return string;
}


void MainWindow::setDateLabs(QDate _date)
{
    //Set Dates
    ui->labMonDate->setText(convertToString(_date));
    ui->labTueDate->setText(convertToString(_date.addDays(1)));
    ui->labWedDate->setText(convertToString(_date.addDays(2)));
    ui->labThuDate->setText(convertToString(_date.addDays(3)));
    ui->labFriDate->setText(convertToString(_date.addDays(4)));
    ui->labSatDate->setText(convertToString(_date.addDays(5)));
    ui->labSunDate->setText(convertToString(_date.addDays(6)));

    setVisibleDateLabs(true);

    _date = _date.addDays(7);

    int y = _date.year();
    int m = _date.month();
    int d = _date.day();

    query.prepare("UPDATE settings SET day = :day, month = :month, year = :year WHERE name = 'current'");
    query.bindValue(":day",   d);
    query.bindValue(":month", m);
    query.bindValue(":year",  y);
    query.exec();
}


void MainWindow::setVisibleDateLabs(bool _visible)
{
    ui->labMonDate->setVisible(_visible);
    ui->labTueDate->setVisible(_visible);
    ui->labWedDate->setVisible(_visible);
    ui->labThuDate->setVisible(_visible);
    ui->labFriDate->setVisible(_visible);
    ui->labSatDate->setVisible(_visible);
    ui->labSunDate->setVisible(_visible);
}


MainWindow::~MainWindow()
{
    delete ui;
}
